import { defineStore } from "pinia";
import { ref } from "vue";
import type { AccountLogin, UserInfo, WxLogin } from "@/types/user";
import { passwordLoginAPI, simpleLoginAPI, wxLoginAPI } from "@/api/userApi";
import { clearUserInfo as removeUserInfo, getUserInfo, setUserInfo } from "@/utils/storage";

const useUserStore = defineStore("userStore", () => {

    /*用户信息*/
    const userInfo = ref<UserInfo>(getUserInfo() || {});

    /*一键登录的请求函数*/
    const simpleLogin = async (phoneNumber: string): Promise<void> => {
        const { result }: { result: UserInfo } = await simpleLoginAPI(phoneNumber);
        userInfo.value = result;
        setUserInfo(result);
    };

    /*用户名密码的请求函数*/
    const passwordLogin = async (data: AccountLogin): Promise<void> => {
        const { result }: { result: UserInfo } = await passwordLoginAPI(data);
        userInfo.value = result;
        setUserInfo(result);
    };

    /*微信登录的请求函数*/
    const wxLogin = async (data: WxLogin): Promise<void> => {
        const { result }: { result: UserInfo } = await wxLoginAPI(data);
        userInfo.value = result;
        setUserInfo(result);
    };

    const clearUserInfo = (): void => {
        userInfo.value = {} as UserInfo;
        removeUserInfo();
    };
    return {
        userInfo,
        simpleLogin,
        passwordLogin,
        wxLogin,
        clearUserInfo,
    };

});

export default useUserStore;
